package com.leetcode.根据数据结构分类.字符串;


/**
 * @author: ZhouBert
 * @date: 2021/1/26
 * @description: 415. 字符串相加
 * https://leetcode-cn.com/leetbook/read/2021-spring-recruitment/5jcm1i/
 */
public class A_415_字符串相加 {
    public static void main(String[] args) {
//        char[] chars = new char[]{' ', 'a'};
//        System.out.println(new String(chars));
        String num1 = "1";
        String num2 = "1";
        A_415_字符串相加 action = new A_415_字符串相加();
        String res = action.addStrings(num1, num2);
        System.out.println("res = " + res);
    }

    /**
     * 由于 new String(chars, offset, count)
     * 所以可以将第三个数组 = maxLen + 1
     *
     * @param num1
     * @param num2
     * @return
     */
    public String addStrings(String num1, String num2) {
        if (num1 == null || num2 == null) {
            return num1;
        }
        int l1 = num1.length();
        int l2 = num2.length();
        int maxLen = Math.max(l1, l2);
        if (maxLen == 0) {
            return "";
        }
        if (l1 == 0) {
            return num2;
        }
        if (l2 == 0) {
            return num1;
        }

        int size = maxLen + 1;
        //上述边界条件已经判断完毕
        int[] resArr = new int[size];
        //进位标志
        boolean flag = false;
        int value = 0;
        for (int i = 1; i <= maxLen; i++) {
            int i1 = l1 < i ? 0 : Integer.parseInt(num1.charAt(l1 - i) + "");
            int i2 = l2 < i ? 0 : Integer.parseInt(num2.charAt(l2 - i) + "");
            value = (i1 + i2);
            if (flag) {
                //如果已经进位
                value++;
            }
            if (value > 9) {
                resArr[size - i] = (value % 10);
                flag = true;
            } else {
                resArr[size - i] = value;
                flag = false;
            }
        }
        int i = 1;
        if (flag) {
            resArr[0] = 1;
            i = 0;
        }

        StringBuilder sb = new StringBuilder();

        for (; i < size; i++) {
            sb.append(resArr[i]);
        }
        return sb.toString();
    }

}
